// src/utils/request.ts
import {message} from 'antd';
import {history} from 'umi';
import {PageResult} from "@/types";

// 定义响应数据结构
interface ApiResponse<T = any> {
    code: number;
    data?: T;
    msg?: string;
    message?: string;
}

// 通用的 API 调用封装
export const callApi = async <T>(
    apiCall: () => Promise<ApiResponse<T>>,
    options: {
        successMsg?: string;
        errorMsg?: string;
        hideSuccessMsg?: boolean;
        hideErrorMsg?: boolean;
    } = {}
): Promise<T | null> => {
    const {
        successMsg,
        errorMsg = '系统异常，工程师已介入，请稍后重试',
        hideSuccessMsg = false,
        hideErrorMsg = false
    } = options;

    try {
        const response = await apiCall();

        // 检查登录状态
        if (response.code === 1051) {
            message.error('登录已过期，请重新登录');
            // 清除本地存储的用户信息
            localStorage.clear();
            // 跳转到登录页
            history.push('/login');
            return null;
        }

        if (response.code === 200) {
            if (successMsg && !hideSuccessMsg) {
                message.success(successMsg);
            }
            return response.data || null;
        } else {
            const errorMessage = response.msg || response.message || errorMsg;
            if (!hideErrorMsg) {
                message.error(errorMessage);
            }
            return null;
        }
    } catch (error: any) {
        console.error('API 调用失败:', error);
        const errorMessage = error?.msg || error?.message || errorMsg;
        if (!hideErrorMsg) {
            message.error(errorMessage);
        }
        return null;
    }
};

// ProTable 专用的请求处理函数
export const handleProTableRequest = async <T>(
    apiCall: () => Promise<ApiResponse<PageResult<T>>>,
    options: {
        errorMsg?: string;
    } = {}
) => {
    const result = await callApi<PageResult<T>>(apiCall, {...options, hideSuccessMsg: true});
    console.log(result);
    return {
        data: result?.list || [],
        success: !!result, // 有结果时为 true，否则为 false
        total: result?.totalCount || 0,
    };
};